<template>
  <div class="app-container">
    <!-- v-powerbtn="{power: 'usercenter-vip-add'}" -->
    <el-button
      type="primary"
      size="mini"
      round
      icon="el-icon-circle-plus-outline"
      class="btnStyle"
      @click="add"
    >新增</el-button>
    <!-- v-powerbtn="{power: 'usercenter-vip-edit'}" -->
    <el-button
      type="primary"
      size="mini"
      round
      icon="el-icon-edit"
      class="btnStyle"
      @click="edit"
    >编辑与删除</el-button>
    <div class="app-table">
      <el-table
        :data="list"
        border
        style="width: 100%"
      >
        <el-table-column label="会员级别" width="200">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="会员等级名称">
          <template slot-scope="scope">
            <template v-if="status">
              <el-input v-model.trim="scope.row.membershipLevelName" autofocus size="small" />
            </template>
            <span v-else>{{ scope.row.membershipLevelName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="成长值范围">
          <template slot-scope="scope">
            <template v-if="status">
              <!-- {{ scope.row.growthValueLower }} -->
              <el-input v-model.number="scope.row.growthValueLower" autofocus size="small" class="edit-input" />
              —
              <!-- {{ scope.row.growthValueUp }} -->
              <el-input v-model.number="scope.row.growthValueUp" :disabled="high[scope.$index]" autofocus size="small" class="edit-input" />
            </template>
            <span v-else>
              <el-tag class="sizeBtn" size="medium" type="primary">{{ scope.row.growthValueLower }}</el-tag>
              <svg-icon icon-class="cc-arrow-right" />
              <el-tag class="sizeBtn" size="medium" type="success">{{ scope.row.growthValueUp }}</el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column v-if="status" label="成长值范围无上限">
          <template slot-scope="scope">
            <el-radio v-model="radio" :label="scope.$index">无上限</el-radio>
          </template>
        </el-table-column>
        <el-table-column v-if="status" label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              type="primary"
              plain
              size="mini"
              icon="el-icon-third-delete"
              @click="deleteVip(scope.row,scope.$index)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-show="status" class="savebtn">
        <el-button
          type="primary"
          size="small"
          round
          style="width:8%;margin-right:20px"
          @click="saveData"
        >保存</el-button>
        <el-button
          type="primary"
          plain
          round
          size="small"
          style="width:8%"
          @click="cancel"
        >取消</el-button>
      </div>
      <!-- <div class="pagination-container">
        <el-pagination
          :current-page="page"
          :page-sizes="[10,20,30,50]"
          :page-size="pageSize"
          :total="total"
          background
          highlight-current-row
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div> -->
    </div>
  </div>
</template>
<script>
import secret from '@/utils/secret'
import { getList, saveVip } from '@/api/vipManage'
import { mapGetters } from 'vuex'
import { positive } from '@/utils/validate'
import powerbtn from '@/directive/powerbtn/index.js'
export default {
  name: 'VipManage',
  directives: {
    powerbtn
  },
  data() {
    return {
      list: null, // 列表项
      status: false,
      count: 0,
      radio: 0, // 单选
      high: [], // 禁选框
      power: null, // 权限
      memberManage_add: false, // 新增
      memberManage_edit: false, // 编辑
      memberManage_dele: false // 删除
    }
  },
  computed: {
    ...mapGetters(['assignment', 'token'])
  },
  watch: {
    // 加入无上限状态
    radio(newVal, oldVal) {
      console.log(newVal, oldVal)
      for (var i = 0; i < this.high.length; i++) {
        if (i === parseInt(newVal)) {
          this.high[i] = true
          this.list[i].growthValueUp = '无上限'
        } else if (i === parseInt(oldVal)) {
          this.high[i] = false
          this.list[i].growthValueUp = ''
        } else {
          this.high[i] = false
        }
      }
    }
  },
  mounted() {
    this.loadList()
    /* var that = this
    console.log(this.assignment) */
    /* this.assignment.forEach(function(item) {
      if (!!item) { // eslint-disable-line
        if (item.menuCode === 'memberManage') {
          that.power = item.btnList
        }
      }
    })
    this.power.forEach(function(item) {
      if (!!item) { // eslint-disable-line
        if (item.code === 'memberManage_add') {
          that.memberManage_add = true
        }
        if (item.code === 'memberManage_edit') {
          that.memberManage_edit = true
        }
        if (item.code === 'memberManage_dele') {
          that.memberManage_dele = true
        }
      }
    }) */
  },
  methods: {
    // 请求列表
    loadList() {
      var token = {
        // token: this.token
      }
      console.log('请求参数')
      // console.log(token)
      getList(secret.Encrypt(token)).then(response => {
        console.log('返回数据')
        console.log(response)
        const data = response.data
        data.list.forEach(function(item) {
          if (!!item) { // eslint-disable-line
            item.edit = false
            item.growthValueLower = parseInt(item.growthThreshold)
            item.growthValueUp = parseInt(item.growthThresholdup)
          }
        })
        this.list = data.list
        this.high = Array(this.list.length).fill(false)
        this.list[0].growthValueUp = '无上限'
        this.high[0] = true
      })
    },
    // 数组去重改良版本
    unique(arr) {
      var res = []
      var repeat = []
      var sortedArray = arr.concat().sort()
      var seen
      for (var i = 0, len = sortedArray.length; i < len; i++) {
        // 如果是第一个元素或者相邻的元素不相同
        if (!i || seen !== sortedArray[i]) {
          res.push(sortedArray[i])
        } else {
          repeat.push(sortedArray[i])
        }
        seen = sortedArray[i]
      }
      return repeat
    // return res;
    },
    // // 当前页数改变时
    // handleSizeChange(num) {
    //   const data = {
    //     token: this.token,
    //     pageid: 1,
    //     pagecount: num
    //   }
    //   getList(secret.Encrypt(data)).then(response => {
    //     this.list = response.data.list // 列表项
    //     this.count = parseInt(response.data.count) // 总数量
    //     this.pages = parseInt(response.data.pages) // 总页数
    //     this.pageid = parseInt(response.data.pageid) // 当前页数
    //     this.pagecount = parseInt(response.data.pagecount) // 当前显示条数
    //     // console.log(response.data)
    //   }).catch(() => {
    //     this.$message({
    //       message: '请求列表失败，请重试',
    //       type: 'error'
    //     })
    //   })
    // },
    // // 跳转某页
    // handleCurrentChange(num) {
    //   const data = {
    //     token: this.token,
    //     pageid: num,
    //     pagecount: this.pagecount
    //   }
    //   // console.log(num)
    //   getList(secret.Encrypt(data)).then(response => {
    //     this.list = response.data.list // 列表项
    //     this.count = parseInt(response.data.count) // 总数量
    //     this.pages = parseInt(response.data.pages) // 总页数
    //     this.pageid = parseInt(response.data.pageid) // 当前页数
    //     this.pagecount = parseInt(response.data.pagecount) // 当前显示条数
    //     // console.log(response.data)
    //   }).catch(() => {
    //     this.$message({
    //       message: '请求列表失败，请重试',
    //       type: 'error'
    //     })
    //   })
    // },
    // 排序
    compare(pro) {
      return function(obj1, obj2) {
        var val1 = obj1[pro]
        var val2 = obj2[pro]
        if (val1 < val2) { // 正序
          return 1
        } else if (val1 > val2) {
          return -1
        } else {
          return 0
        }
      }
    },
    // 编辑
    edit() {
      this.status = true
    },
    // 取消
    cancel() {
      this.loadList()
      this.status = false
      this.count = 0
      this.radio = 0
    },
    // 增加
    add() {
      this.status = true
      this.list.push({
        edit: false,
        membershipLevel: parseInt(this.list.length) + 1,
        growthThreshold: null,
        growthThresholdup: null,
        membershipLevelId: null,
        growthValueLower: null,
        growthValueUp: null,
        membershipLevelName: '新增'
      })
      this.high.push(false)
      this.high[0] = true
      this.count = this.count + 1
    },
    // 删除
    deleteVip(data, index) {
      // console.log(data, index)
      this.$confirm('删除会员等级后，建议重新配置会员成长值范围确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(data)
        // 判断无上限问题
        this.list.splice(index, 1)
        if (data.growthValueUp === '无上限') {
          this.$set(this.list[index], 'growthValueUp', '无上限')
        }
        console.log(index)
        // this.$set(this.list, index)
        // this.$message({
        //   type: 'success',
        //   message: '删除成功'
        // })
      }).catch(() => {
        console.log('删除取消')
      })
    },
    // 保存
    saveData() {
      this.radio = 0
      // 此方法下判断回调太多，想用promise方法，待定
      var oldData = this.list
      // 校验会员名是否重复
      // 检查有没有0
      var zero = []
      var endd = []
      this.list.forEach(function(item) {
        if (!!item) { // eslint-disable-line
          for (const obj in item) {
            if (obj === 'growthValueLower') {
              zero.push(item['growthValueLower'])
            }
            if (obj === 'growthValueUp') {
              endd.push(item['growthValueUp'])
            }
          }
        }
      })
      if (zero.indexOf(null) > 0 || endd.indexOf(null) > 0) {
        this.$message({
          message: '成长值不可为空',
          type: 'error'
        })
        return
      }
      if (zero.indexOf(0) < 0) {
        this.$message({
          message: '成长值范围配置最小值需从0开始',
          type: 'error'
        })
        return
      }
      var repeatName = [] // 会员名字
      var allData = [] // 全部范围数字
      oldData.forEach(function(item) {
        if (!!item) { // eslint-disable-line
          for (var i in item) {
            if (i === 'membershipLevelName') {
              repeatName.push(item[i])
            }
            if (i === 'growthValueLower' || i === 'growthValueUp') {
              allData.push(item[i])
            }
          }
        }
      })
      // 检查会员名是否重复和是否为空
      if (repeatName.indexOf('') > 0) {
        this.$message({
          message: '会员等级名称不可为空',
          type: 'error'
        })
        return
      }
      var repe = []
      repe = repeatName.filter(function(item, index) {
        return repeatName.indexOf(item) !== index
      })
      console.log(repe)
      if (repe.length > 0) {
        this.$message({
          message: '会员等级名称重复',
          type: 'error'
        })
        repe = []
        return
      }
      // var newName = this.unique(repeatName)
      var repeatNums = this.unique(allData)
      if (repeatNums.length > 0) {
        this.$message({
          message: '各级会员的成长值范围不可重叠',
          type: 'error'
        })
        return
      }
      // 这个数组的作用是等allData校验全部通过后再执行下一步操作
      var middle = []
      // 校验等级范围是否符合 !parseInt(allData[m])
      for (let m = 0; m < allData.length; m++) {
        if (allData[m] !== 0 && allData[m] !== '无上限' && !positive(allData[m])) {
          console.log(1)
          this.$message({
            message: '成长值标准仅可以为正整数',
            type: 'error'
          })
          return
        } else {
          console.log(3)
          middle.push(allData[m])
        }
      }
      if (middle.length === allData.length) {
        var middleData = []
        oldData.sort(this.compare('growthValueLower'))
        for (let i = 0; i < oldData.length - 1; i++) {
        // 检查是否重复
          if (oldData[i].growthValueLower > oldData[i + 1].growthValueUp + 1) {
            this.$message({
              message: '相邻两级会员成长值范围之间不可留有空档',
              type: 'error'
            })
            break
          } else if (oldData[i].growthValueLower < oldData[i + 1].growthValueUp + 1) {
            this.$message({
              message: '各级会员的成长值范围不可重叠！',
              type: 'error'
            })
            break
          } else {
            middleData.push(oldData[i])
          }
        }
        if (middleData.length === oldData.length - 1) {
          // if (newName.length > 0) {
          //   this.$message({
          //     message: '会员名' + newName[0] + '已存在',
          //     type: 'error'
          //   })
          // } else {
          this.list[0].growthValueUp = ''
          var newList = this.list
          newList.forEach(function(item) {
            if (!!item) { // eslint-disable-line
              for (const g in item) {
                if (item[g] === null) {
                  delete item[g]
                }
                if (g === 'edit') {
                  delete item[g]
                }
                if (g === 'growthThreshold') {
                  item[g] = item.growthValueLower
                  delete item.growthValueLower
                }
                if (g === 'growthThresholdup') {
                  item[g] = item.growthValueUp
                  delete item.growthValueUp
                }
              }
            }
          })
          var data = {
            // token: this.token,
            membersList: newList
          }
          console.log('请求参数')
          console.log(data)
          saveVip(secret.Encrypt(data)).then(response => {
            console.log('返回数据')
            console.log(response)
            if (response) {
              if (response.resultCode === '0000') {
                this.$message({
                  message: response.resultDesc,
                  type: 'success'
                })
                this.status = false
                this.loadList()
              } else {
                this.$message({
                  message: response.resultDesc,
                  type: 'error'
                })
              }
            } else {
              this.cancel()
              this.status = true
            }
          })
          // }
        }
      }
    }
  }
}
</script>
<style scoped>
  .edit-input{
    width: 30%;
  }
  .savebtn{
    display: flex;
    justify-content: center;
    margin-top: 20px;

  }
</style>
<style>
  .sizeBtn{
    min-width: 60px;
  }
</style>

